package homework;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 采用lock + condition
 */
public class Method04 {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private volatile Integer value = null;

    //存储返回结果
    private void sum(int num) {
        lock.lock();
        try{
            value =  fibo(num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    private int fibo(int a) {
        if ( a < 2)
            return 1;
        return fibo(a-1) + fibo(a-2);
    }

    public int getValue() throws InterruptedException {
        lock.lock();
        try {
            while (null == value){
                condition.await();
            }
        }finally {
            lock.unlock();
        }
        return value;
    }

    public static void main(String[] args) throws InterruptedException {

        long start=System.currentTimeMillis();

        Method04 method = new Method04();
        // 在这里创建一个线程或线程池，异步执行 下面方法
        Thread thread = new Thread(() -> {
            method.sum(36);
        });
        thread.start();
        thread.join();
         //这是得到的返回值
        int result = method.getValue();
        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + result);

        System.out.println("使用时间："+ (System.currentTimeMillis()-start) + " ms");
        // 然后退出main线程
    }

}
